package task;

/**
 * Creared with IntelliJ IDEA.
 * Description:阻塞队列案例
 * User:yxd
 * Date:2022-03-29
 * Time:9:29
 */
class MyBlockingQueue{
    //存放数据的数组
    private int[] nums = new int[1000];
    //有效元素个数
    private int size;
    //队首下标
    private int head;
    //队尾下标
    private int tail;
    //入队方法
    public void put(int val) throws InterruptedException {
        synchronized (this){
            if(size == nums.length){
                this.wait();//进入阻塞直至有元素出队后
            }
            nums[tail] = val;
            tail ++;
            if(tail >= nums.length){
                tail = 0;
            }
            size ++;
            //此时便可唤醒出队时的等待
            this.notify();
        }
    }
    public int take() throws InterruptedException {
        synchronized (this){
            if(size == 0){
                this.wait();//进入阻塞直至有元素入队后
            }
            int ret = nums[head];
            head ++;
            if(head >= nums.length){
                head = 0;
            }
            size --;
            this.notify();//此时便可唤醒入队时的等待
            return ret;
        }
    }

}
public class Practice_2 {
    public static void main(String[] args) {
        MyBlockingQueue queue = new MyBlockingQueue();
        Thread t1 = new Thread(()->{
           int num = 0;
           while(true){

               try {
                   System.out.println("生产:" + num);
                   queue.put(num);
                   num ++;
                   //Thread.sleep(600);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }

           }
        });
        t1.start();
        Thread t2 = new Thread(()->{
           while(true){
               try {
                   int val = queue.take();
                   System.out.println("消费:" +val);
                   Thread.sleep(600);
               } catch (InterruptedException e) {
                   e.printStackTrace();
               }
           }
        });
        t2.start();
    }
}
